#include <stdio.h>
#include "../global.h"
#include <string.h>
#include "stack.h"

/*
* 栈空间可以是 静态的栈中，也可以动态的申请
* 栈的初始化
* 栈 增
* 栈 减
* 获取栈的大小
* 获取当前栈的长度
* 判断栈是否为空
* 打印出栈中的所有数据
* 栈的销毁
*/
int stkArray[STACKSIZE];

void InitStack(STACK* stk,void* stkPointer)
{
	stk->stkPointer = stkPointer;
	stk->size = STACKSIZE;
	stk->top = -1;
	memset(stk->stkPointer,0,stk->size);
}

/*
* 0-fail 1-success,如果入栈的数据是char类型咋办？用指针？const int* const data
*/
int PushStack(STACK* stk,const int* const data)
{
	if(stk->stkPointer == NULL) return 0;
	if(stk->top >= STACKSIZE)  //>= or ==
	{
		printf("Stack is overflow!!!\n");
		return 0;
	}
	stk->top++;
	stk->stkPointer[stk->top] = *data;
	
	
	return 1;
}

/*
* 
*/
int PopStack(STACK* const stk)
{
	int tmp = 0;
	if(stk->stkPointer == NULL) return INTERROR;
	tmp = stk->stkPointer[stk->top];
	stk->top--;
	return tmp;
}

/*
* 获取栈的大小
*/
int SizeStack(STACK* stk)
{
	return stk->size;
}

/*
* 打印出栈的所有元素,从栈顶开始打印
*/
void PrintStack(STACK* stk)
{
	int i = 0;
	
	for(i=stk->top;i>=0;i--)  //用小于0好还是 ==-1好？
	{
		printf("%d\n",stk->stkPointer[i]);
		
	}
}

/*
* 释放当前栈空间
*/
void FreeStack(STACK* stk)
{
	FREE(stk->stkPointer);
}


/*
* 获取当前栈的长度
*/
int LenStack(STACK* stk)
{
	return stk->top;
}

/**
 * 判断栈是否空
 * empety-1 not empety-0
 * */
int IsStackEmpety(STACK* stk)
{
	if(stk->top <0) return 1;
	else 			return 0;
}

//free 掉不是堆上的空间编译不会报错
/*
free(): invalid size
Aborted (core dumped)
*/
#ifdef STACK_DEBUG
int main(int argc, char const *argv[])
{
	
	int i = 0;
	STACK* stk;
	int* stkPointer = (int*)malloc(sizeof(int)*STACKSIZE);
	
	InitStack(stk,(int*)stkPointer);
	printf("stkPointer is %p  stk->stkPointer is %p\n",stkPointer,stk->stkPointer);
	//int* p = stk->stkPointer;
	for(i=0;i<STACKSIZE;i++)
	{
		PushStack(stk,&i);
	}
	printf("stk->top is %d\n",stk->top);
	
	PrintStack(stk);
	


	printf("---------------------------\n");
	//FREE(stkPointer);
	FreeStack(stk);
	return 0;
}

#endif